//index.js
//获取应用实例
const app = getApp()
var api = require("../../utils/api.js")
var QQMapWX = require('../../utils/qqmap/qqmap-wx-jssdk.js');
var address = require('../../utils/city.js').JsonData;
var qqmapsdk;
Page({
  data: {
    longitude: 105.57221982945505,
    latitude: 42.24870531297644,
    scale: 3,
    statistics: {},
    markers: [],
    isSelect: 1,
    str: '请选择年份',
    strImg: '../../images/date.png',
    isMenuHidden: true,
    mapHeight: 'calc(100vh - 294rpx)',
    searchBackHeight: 0,
    listBackHeight: 0,
    isSeach: false,
    isBackHidden: false,
    isSelectList: -1,
    isShowLocation: false,
    searchValue: '',
    address: '', //详细收货地址（四级）
    value: [0, 0, 0], // 地址选择器省市区 暂存 currentIndex
    region: '', //所在地区
    regionValue: [0, 0, 0], // 地址选择器省市区 最终 currentIndex
    provinces: [], // 一级地址
    citys: [], // 二级地址
    areas: [], // 三级地址
    visible: false,
    addressId: '', // 数据库内地址编号
    type: 1,
    province_name: '请选择',
    city_name: '',
    provinceNum: -1,
    district_name: '',
    filterArray: [],
    paramsData: {},
    scaleParams: 4,
    locationList: []
  },
  onLocation(e) {
    let id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: '../country/index?id=' + id
    })
  },
  onUser(e) {
    let id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: '../spokesman/index?id=' + id
    })
  },
  cityChange2(e) {
    let {
      provinces
    } = this.data
    let cityNum = e.currentTarget.dataset.id
    this.setData({
      city_name: e.currentTarget.dataset.name,
      cityNum: cityNum,
      type: e.currentTarget.dataset.type,
      district_name: "请选择",
      areas: address.areas[e.currentTarget.dataset.id]
    })
  },
  cityChange3(e) {
    this.setData({
      district_name: e.currentTarget.dataset.name,
      type: e.currentTarget.dataset.type,
    })
  },
  cityChangTap(e) {
    var value = e.detail.value
    if (e.currentTarget.dataset.type == 1) {
      this.setData({
        city_name: "请选择",
        district_name: "",
        type: e.currentTarget.dataset.type,
      })
    } else if (e.currentTarget.dataset.type == 2) {
      this.setData({
        district_name: "",
        type: e.currentTarget.dataset.type,
      })
    }

  },
  // 处理省市县联动逻辑 并保存 value
  cityChange(e) {
    var value = e.detail.value
    this.setData({
      province_name: e.currentTarget.dataset.name,
      provinceNum: e.currentTarget.dataset.id,
      type: e.currentTarget.dataset.type,
      city_name: "请选择",
      district_name: "",
      citys: address.citys[e.currentTarget.dataset.id]
    })
  },
  onNavBack() {
    let that = this;
    let height = wx.getSystemInfoSync().windowHeight
    that.setData({
      isShowLocation: false,
      searchBackHeight: (height * 2) - 30,
      listBackHeight: 0,
    })
  },
  onSelectList(e) {
    let that = this;
    let value = e.currentTarget.dataset.value;
    let item = e.currentTarget.dataset.item
    let type = e.currentTarget.dataset.type
    let height = wx.getSystemInfoSync().windowHeight
    let searchValue = ''
    let data = {}
    if (type == 1) {
      searchValue = item.samplingDate
      data = {
        scale: 4,
        createdTime: item.samplingDate
      }
    } else if (type == 3) {
      searchValue = item.teamName
      data = {
        scale: 4,
        teamId: item.id
      }
    } else if (type == 4) {
      searchValue = item.tagName
      data = {
        scale: 4,
        status: item.id
      }
    } else if (type == 5) {
      searchValue = item.sponsorName
      data = {
        scale: 4,
        sponsorId: item.id,
        type: 'wechat'
      }
    }
    that.setData({
      scaleParams: 4,
      // scale: 3
    })
    var url = app.u.url + app.u.index.SelectListVillage;
    api.requestUrl(data, url).then(res => {
      let list = res.data.list
      if (list.length > 0) {
        that.setData({
          isSelectList: value,
          isShowLocation: true,
          searchBackHeight: 0,
          listBackHeight: (height * 2) - 30,
          searchValue: searchValue,
          locationList: list
        })
      } else {
        wx.showToast({
          title: '暂无数据',
          icon: 'success',
          duration: 2000
        })
        that.setData({
          isSelectList: value,
          searchValue: ''
        })
      }
    });
  },
  onSeachBack() {
    this.setData({
      mapHeight: ' calc(100vh - 294rpx)',
      searchBackHeight: 0,
      isSeach: false,
      isBackHidden: false,
      searchValue: '',
      isSelectList: -1,
    })
  },
  onSeach() {
    let height = wx.getSystemInfoSync().windowHeight
    if (this.data.isSelect == 2) {
      // 默认联动显示北京
      this.setData({
        type: 1,
        province_name: '请选择',
        city_name: '',
        district_name: '',
      })
    }
    this.setData({
      mapHeight: '222rpx',
      searchBackHeight: (height * 2) - 30,
      isSeach: true,
      isBackHidden: true,
    })
  },
  onImgClick() {
    this.setData({
      isMenuHidden: false
    })
  },
  // 左侧菜单点击事件
  onSelect(e) {
    let that = this;
    let value = e.currentTarget.dataset.value;
    let strText = ''
    let strImg = ''
    if (value == 1) {
      strText = '请选择年份'
      strImg = '../../images/date.png'
    } else if (value == 2) {
      strText = '请选择省/市/县'
      strImg = '../../images/shen.png'
      // 默认联动显示北京
      var id = address.provinces[0].id
      that.setData({
        provinces: address.provinces,
        citys: address.citys[id],
        areas: address.areas[address.citys[id][0].id]
      })
    } else if (value == 3) {
      strText = '请选择团队'
      strImg = '../../images/team.png'
    } else if (value == 4) {
      strText = '请选择标签'
      strImg = '../../images/biaoqian.png'
    } else if (value == 5) {
      strText = '请选择合作方'
      strImg = '../../images/hezuo.png'
    }
    that.setData({
      isSelect: value,
      str: strText,
      strImg: strImg,
    })
  },
  // 搜索
  confirmTap: function(event) {
    let that = this;
    let type = event.currentTarget.dataset.isselect
    let text = event.detail.value.searchText.replace(/ /g, ",");
    if (type == 2) {
      let data = {
        scale: 4,
        areaName: text,
        type: 'wechat'
      }
      that.setData({
        scaleParams: 4,
        scale: 7,
        paramsData: {
          areaName: event.detail.value.searchText
        }
      })
      var url = app.u.url + app.u.index.SelectListVillage;
      api.requestUrl(data, url).then(res => {
        let list = res.data.list
        let markers = res.data.markers
        if (list.length > 0) {
          let height = wx.getSystemInfoSync().windowHeight
          that.setData({
            isShowLocation: true,
            searchBackHeight: 0,
            listBackHeight: (height * 2) - 30,
            locationList: list
          })
        } else {
          wx.showToast({
            title: '暂无数据',
            icon: 'success',
            duration: 2000
          })
        }
      });
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    let that = this;
    wx.showLoading({
      title: '加载中',
    })
    qqmapsdk = new QQMapWX({
      key: '46de65662a4021bc5de9acc206a65f09' // 必填
    });
    wx.getLocation({
      type: 'gcj02',
      success: function(resCode) {
        qqmapsdk.reverseGeocoder({
          location: {
            latitude: resCode.latitude,
            longitude: resCode.longitude
          }
        })
      }
    })
    that.onTag();
    let data = {
      scale: 1
    }
    that.setData({
      scaleParams: 1,
      scale: 3
    })
    that.onMarkers(data);
    that.onStatistics(data);
  },
  regionchange(e) {
    let that = this;
    if (e.type == 'end' && (e.causedBy == 'scale')) {
      that.mapCtx = wx.createMapContext("map");
      that.mapCtx.getScale({
        type: 'gcj02',
        success: function(res) {
          if (res.scale <= 4) {
            if (that.data.scaleParams !== 1) {
              if (that.data.paramsData.areaName !== undefined) {
                delete that.data.paramsData.areaName
                that.data.searchValue = ''
              }
              let data = {
                scale: 1
              }
              that.setData({
                scaleParams: 1,
                // scale: 3
              })
              that.onMarkers(data);
              that.onStatistics(data);
            }
          } else if (res.scale >= 7) {
            if (that.data.scaleParams !== 4) {
              console.log('else')
              let data = {
                scale: 4
              }
              that.setData({
                scaleParams: 4,
                // scale: 7,
              })
              that.onMarkers(data);
            }
          }
        }
      })
    }
  },
  bindcallouttap(e) {
    let that = this;
    let markers = that.data.markers[e.markerId]
    if (that.data.paramsData.areaName != undefined) {
      wx.navigateTo({
        url: '../country/index?id=' + markers.item.locationId
      })
      that.data.markers[e.markerId].iconPath = "../../images/quanSelect.png"
      that.setData({
        markers: that.data.markers
      })
    } else {
      let data = {
        areaName: markers.item.province,
        scale: 4
      }
      that.setData({
        scaleParams: 4,
        scale: 7,
        paramsData: {
          areaName: markers.item.province
        }
      })
      that.onMarkers(data);
    }
  },
  onMarkers(params) {
    let that = this;
    params.type = 'wechat'
    var url = app.u.url + app.u.index.SelectListVillage;
    api.requestUrl(params, url).then(res => {
      let array = res.data.list
      if (array.length > 0) {
        if (params.areaName) {
          let location = res.data.location
          that.setData({
            latitude: location.centerLat,
            longitude: location.centerLng,
          })
        }
        if (params.scale == 1) {
          that.setData({
            longitude: 105.57221982945505,
            latitude: 42.24870531297644,
          })
        }
        that.setData({
          markers: res.data.markers
        })
      } else {
        wx.showToast({
          title: '暂无数据',
          icon: 'success',
          duration: 2000
        })
      }
      setTimeout(function() {
        wx.hideLoading()
      }, 500)
    });
  },
  onTag() {
    let that = this;
    var url = app.u.url + app.u.index.GetTagItem;
    api.requestUrl({}, url).then(res => {
      let filterArray = res.data
      that.setData({
        filterArray: res.data
      })
    });
  },
  onStatistics() {
    let that = this;
    var url = app.u.url + app.u.index.Statistics;
    api.requestUrl({}, url).then(res => {
      let statistics = res.data
      that.setData({
        statistics: statistics
      })
    });
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  }
})